package com.xiaoyu.lanling.feature.view

import android.content.Context
import android.util.AttributeSet
import android.view.SoundEffectConstants
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.Checkable
import androidx.appcompat.widget.AppCompatImageButton
import com.github.florent37.viewanimator.ViewAnimator

class ImageCheckableAnimButton : AppCompatImageButton, Checkable {

    companion object {
        private val CHECK_STATE = intArrayOf(android.R.attr.state_checked)
    }

    private var mOnCheckedChangeListener: OnCheckedChangeListener? = null

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun onCreateDrawableState(extraSpace: Int): IntArray {
        val states = super.onCreateDrawableState(extraSpace + 1)
        if (isChecked) {
            View.mergeDrawableStates(states, CHECK_STATE)
        }
        return states
    }

    override fun setChecked(checked: Boolean) {
        if (isSelected != checked) {
            isSelected = checked
            mOnCheckedChangeListener?.onCheckedChanged(this, checked)
            refreshDrawableState()
            animCheck(checked)
        }
    }

    override fun isChecked(): Boolean {
        return isSelected
    }

    override fun toggle() {
        isSelected = !isSelected
    }

    override fun performClick(): Boolean {
        if (isSelected) {
            return true
        }
        toggle()
        val handled = super.performClick()
        if (!handled) {
            /*
             * View only makes a sound effect if the onClickListener was
             * called, so we'll need to make one here instead.
             */
            playSoundEffect(SoundEffectConstants.CLICK)
        }
        return handled
    }

    private fun animCheck(checked: Boolean) {
        if (checked) {
            ViewAnimator.animate(this)
                    .scale(1f, 1.12f)
                    .interpolator(AccelerateDecelerateInterpolator())
                    .duration(200)
                    .start()
        } else {
            ViewAnimator.animate(this)
                    .scale(1.12f, 1f)
                    .interpolator(AccelerateDecelerateInterpolator())
                    .duration(200)
                    .start()
        }
    }

    fun setOnCheckedChangeListener(listener: OnCheckedChangeListener?) {
        mOnCheckedChangeListener = listener
    }

    interface OnCheckedChangeListener {
        fun onCheckedChanged(buttonView: ImageCheckableAnimButton?, isChecked: Boolean)
    }
}